package com.cy.lib.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

/**
 * Created by CY on 2015/11/11.
 *
 * @title 空视图 适用任何视图
 * @使用方式 EmptyView 当作父控件视图容器
 */
public class EmptyView extends FrameLayout {

    TextView mTvEmpty;

    public EmptyView(Context context) {
        super(context);
    }

    public EmptyView(Context context, AttributeSet attrs) {
        super(context, attrs);
//        showEmptyView();
        init();
    }

    public EmptyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public EmptyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void showEmptyView() {
        if (mTvEmpty == null || TextUtils.isEmpty(mTvEmpty.getText())) {
            showEmptyView("Loading...");
        } else {
            showEmptyView(mTvEmpty.getText());
        }
    }

    public void showEmptyView(CharSequence text) {
        showEmptyView(text, null);
    }

    public void showEmptyView(int resource) {
        showEmptyView(getResources().getString(resource), null);
    }

    public void showEmptyView(int resource, OnClickListener listener) {
        showEmptyView(getResources().getString(resource), listener);
    }

    private void init() {
        mTvEmpty = new TextView(getContext());
        mTvEmpty.setGravity(Gravity.CENTER);
        mTvEmpty.setTextAppearance(getContext(), android.R.style.TextAppearance_DeviceDefault_Medium);
    }

    public void showEmptyView(CharSequence text, OnClickListener listener) {
        mTvEmpty.setText(text);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        addView(mTvEmpty, getChildCount(), params);
        mTvEmpty.setOnClickListener(listener);
    }

    @Deprecated
    public void hideEmptyView() {
        removeEmptyView();
    }

    public void removeEmptyView() {
        removeView(mTvEmpty);
    }

}
